package com.atguigu.gulimall.authserver.controller;


import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.BizCodeEnume;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.authserver.feign.MemberFeignService;
import com.atguigu.gulimall.authserver.feign.SmsFeign;
import com.atguigu.gulimall.authserver.vo.UserLoginVo;
import com.atguigu.gulimall.authserver.vo.UserRegistVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@Controller
public class LoginController {

    @Autowired
    SmsFeign smsFeign;


    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @Autowired
    MemberFeignService memberFeignService;

    /**
     * Author : hmy
     *
     * @date 2021/9/19 22:00
     * desc : 通过WebMvcConfiguer来配置页面的跳转
     **/

    @GetMapping("/websuccess")
    public String loginRedict(UserRegistVo userRegistVo,HttpSession session) {
        R login = memberFeignService.login(userRegistVo);
        if(login.getCode() ==0){
            UserLoginVo data = login.getData2("data",new TypeReference<UserLoginVo>(){});
            log.info("登录成功 用户{}"+data);
            session.setAttribute("loginUser",data);
            return "redirect:http://gulimail110/"; //登录成功，返回首页
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }
//
//    @GetMapping("/reg.html")
//    public String regRedict() {
//        return "register";
//    }
    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo,RedirectAttributes model) {
        UserRegistVo userRegistVo = new  UserRegistVo();
        BeanUtils.copyProperties(userLoginVo,userRegistVo);
        R login = memberFeignService.login(userRegistVo);
        if(login.getCode() == 0){
            return "redirect:http://gulimail110";
        }
        Map<String, String> errors = new HashMap<>();
        errors.put("msg", login.getData2("msg",new TypeReference<String>(){}));
        model.addFlashAttribute("errors", errors);
        return "redirect:http://auth.gulimall.com/login.html";
    }


    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        if (StringUtils.isEmpty(phone)) {
            return R.error("手机号不能为空");
        }
        Integer phoneNumber = (int) ((Math.random() * 9 + 1) * 100000);
        String codeTime = String.valueOf(phoneNumber) + "_" + System.currentTimeMillis();
        String phoneCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);

        //为空的可以发送验证码
        if (StringUtils.isEmpty(phoneCode)) {
            smsFeign.sendMsg(phone, String.valueOf(phoneNumber));
            stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, codeTime, 10, TimeUnit.MINUTES);
            return R.ok();
        }
        //小于60秒，不能发送验证码
        String startTime = phoneCode.split("_")[1];
        Long startTimeLong = Long.valueOf(startTime);
        if ((System.currentTimeMillis() - startTimeLong) < 60000) {
            return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMeg());
        } else {
            //可以发送验证码
            smsFeign.sendMsg(phone, phoneCode.split("_")[0]);
            stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, codeTime, 10, TimeUnit.MINUTES);
            return R.ok();
        }
    }


    @PostMapping("/regist")
    public String registry(@Valid UserRegistVo userRegistVo, BindingResult bindingResult, RedirectAttributes model
//                           Model model  转发使用的，重新向使用RedirectAttributes 但是只有一次，使用后就销毁，所以产生session共享的问题
    ) {

        //重定向携带数据，利用session原理，将数据放在session中，只要跳转到下一个页面取出这一个数据以后，session里面的数据就会删除掉
        //分布式下的session问题
        if (bindingResult.hasErrors()) {
//             //如果校验出错的话，就会转发到注册页
//              return "register";
            Map<String, String> collect = bindingResult.getFieldErrors()
                    .stream()
                    .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            model.addFlashAttribute("errors", collect);
            //转发，路径不变，如果刷新，就是一次重复提交，所以需要使用重定向的方式
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        // 校验没有错误，就可以进行相应的业务逻辑
        //1:校验验证码
        String code = userRegistVo.getCode();
        String phone = userRegistVo.getPhone();
        String redisKey = AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone;
        //2：判断验证码是不是合法的
        String redisCode = stringRedisTemplate.opsForValue().get(redisKey);
        //因为验证码加了系统时间，所以需要截取字符串  获取验证码不为空，且验证码通过，其余两种情况都是错误的，那么都得跳转到对应的注册页面
        if (!StringUtils.isEmpty(redisCode)) {
            String deatCode = redisCode.split("_")[0];
            if (code.equals(deatCode)) {
                //相同说明验证码正确，然后调用远程服务
                R register = memberFeignService.register(userRegistVo);
                if (register.getCode() == 0) {
                    //成功
                    //删除，防止拿之前的 验证码来进行操作数据
                    stringRedisTemplate.delete(redisKey);
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    //如果失败的话，会将调用接口失败的信息返回的
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", register.getData2("msg",new TypeReference<String>(){}));
                    model.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            }
        }
        //如果验证码不存在的话，说明需要跳转到对应的注册页
        Map<String, String> errors = new HashMap<>();
        errors.put("code", "验证码错误");
        model.addFlashAttribute("errors", errors);
        return "redirect:http://auth.gulimall.com/reg.html";
        //注册成功回到首页，回到登录页
//        return "redirect:/login.html";
    }


}
